package cn.stylefeng.guns.modular.system.service.impl;

import cn.stylefeng.guns.modular.dto.ProxyUserDTO;
import cn.stylefeng.guns.modular.system.entity.UserInfoRes;
import cn.stylefeng.guns.modular.system.dao.ProxyUserMapper;
import cn.stylefeng.guns.modular.system.enums.ResultEnum;
import cn.stylefeng.guns.modular.system.exception.ProjectException;
import cn.stylefeng.guns.modular.system.service.ProxyUserService;
import cn.stylefeng.guns.modular.system.vo.SubagentVO;
import cn.stylefeng.guns.sys.core.constant.state.ManagerStatus;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.utils.SysUtil;
import cn.stylefeng.roses.core.util.MD5Util;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName ProxyUserServiceImpl
 * @Author lzy
 * @Date 2020/1/6 11:37
 * @VERSION 1.0
 **/

@Service
public class ProxyUserServiceImpl extends ServiceImpl<ProxyUserMapper, User> implements ProxyUserService {
private final static Logger log = LoggerFactory.getLogger(ProxyUserServiceImpl.class);

    public static final String columnNamePre = "ppid";
    @Override
    public Integer getAccountCount(String phone) {
        return baseMapper.getAccountCount(phone);
    }

    @Override
    public List<String> findSubUserIdList(String id) {
        //需要根据id和level查询sys_dlht_user_relation表中的所有子代理id
        Map<String,Object> userRelationMap = baseMapper.selectRelationByPid(id);
        if (ObjectUtils.isEmpty(userRelationMap.get("pid"))){
            throw new ProjectException(ResultEnum.SITE_UPDATE_ERROR);
        }
        String columnName = columnNamePre +  userRelationMap.get("level").toString();
        List<String> subUserIds = baseMapper.findSubUserIdList(columnName,id);
        log.info(id + "代理用户的所有的子代理id为:" +  Arrays.toString(subUserIds.toArray()));
        return subUserIds;
    }

    @Override
    public List<User> selectProxyByUserId(String userId) {
        return baseMapper.selectProxyByUserId(userId);
    }


    @Override
    @Transactional
    public void insertProxyUser(SubagentVO subagentVO) {
        //TODO 这里测试的时候看一下前端传过来的数据是不是bigdecimal类型的，如果报错或者接收不到值，就用double接收，然后new一个bigdecimal出来转换即可
        BigDecimal feilv = limitLength(subagentVO.getExchangeRate());
        //当前代理设置分代理需要根据自己的代理级别来设置自分代理费率，并且不能大于。所以，查询出当前user
        User user = this.selectUserById(subagentVO.getSuperiorAgentId());
        //自己的费率
        BigDecimal exchangeRate = user.getExchangeRate();
        //小比大-1    大比小1   一样大0
        if(exchangeRate.compareTo(feilv) == -1){
            throw new ProjectException(ResultEnum.OVERSIZED_RATES);
        }
        log.info("代理创建子代理-----费率：" +subagentVO.getExchangeRate());

        //生成六位随机盐
        String salt = SysUtil.getSalt();
        //TODO 密码加密方式为MD5双层加密      password+email+phone+salt
        String newPassword = MD5Util.encrypt(MD5Util.encrypt(subagentVO.getPassword()
                + subagentVO.getEmail() + subagentVO.getPhone() + salt));

        ProxyUserDTO build = ProxyUserDTO.builder()
                .userId(IdWorker.getId()+ "")
                .account(subagentVO.getPhone())
                .createTime(new Date())
                .email(subagentVO.getEmail())
                .exchangeRate(feilv)
                .name(subagentVO.getName())
                .password(newPassword)
                .salt(salt)
                .status(ManagerStatus.APPROVAL.getCode())
                .roleId("1")
                .phone(subagentVO.getPhone())
                .superiorAgentId(subagentVO.getSuperiorAgentId())
                .updateTime(new Date())
                .build();
        log.info("注册的账号信息为：" + build.toString());
        baseMapper.insertProxyUser(build);
        log.info("返回添加的用户id为：" + build.getUserId());
        //根据添加人id查询的代理关系，并为被添加人新增代理关系
        Map<String,Object> userRelationMap = baseMapper.selectRelationByPid(user.getUserId().toString());
        int level = (int) userRelationMap.get("level");
        //使用集合存储被添加人的ppid,level作为循环次数，将添加人的ppid存入集合中
        List columnNames = new ArrayList();//要添加的字段
        List ppidValues = new ArrayList();//ppid字段的值
        Map<String,Object> newUserRelationMap = new HashMap<String,Object>();//被添加人的代理关系数据
        for (int i = 1; i <= level; i++) {
            if (i == level){
                columnNames.add(columnNamePre + i);
                ppidValues.add(userRelationMap.get("pid").toString());
            }else {
                columnNames.add(columnNamePre + i);
                ppidValues.add(userRelationMap.get(columnNamePre + i));
            }
        }
        log.info("被添加人的columnNames为：" + Arrays.toString(columnNames.toArray()));
        log.info("被添加人的ppidValues为：" + Arrays.toString(ppidValues.toArray()));
        newUserRelationMap.put("columnNames",columnNames);
        newUserRelationMap.put("ppidValues",ppidValues);
        newUserRelationMap.put("pid",build.getUserId());
        newUserRelationMap.put("level",(int)userRelationMap.get("level") + 1);
        int result = this.baseMapper.insertUserRelation(newUserRelationMap);
        if (result < 1){
            //添加失败，记录回滚
            throw new ProjectException(ResultEnum.SITE_UPDATE_ERROR);
        }
    }

    @Override
    public User selectUserById(Long superiorAgentId) {
        return baseMapper.selectById(superiorAgentId);
    }



    @Override
    public List<UserInfoRes> findListByCondition(String startTime, String endTime, String account, String name,  List<String> subUserIds) {
        if(!ObjectUtils.isEmpty(account)){
            account = account + "%";
        }
        if(!ObjectUtils.isEmpty(name)){
            name = name + "%";
        }
        if(subUserIds.size() == 0 || ObjectUtils.isEmpty(subUserIds)){
            return null;
        }
        List<UserInfoRes> listByCondition = baseMapper.findListByCondition(startTime, endTime, account, name, subUserIds);
        return listByCondition;
    }

    @Override
    @Transactional
    public void updateRate(Long userId, BigDecimal exchangeRate) {
        BigDecimal feilv = limitLength(exchangeRate);
        baseMapper.updateRate(userId,feilv);
    }

    @Override
    @Transactional
    public void updateProxy(ProxyUserDTO build) {
        baseMapper.updateProxy(build);
    }

    @Override
    @Transactional
    public void deleteProxy(Long id) {
        baseMapper.deleteProxy(id);
    }

    @Override
    public User selectProxy(Long id) {
        return baseMapper.selectById(id);
    }



    /**
     * 限制费率长度
     * @param feilv
     * @return
     */
    public BigDecimal limitLength(BigDecimal feilv){
        //限制传过来的数据小数点只能有一位
        BigDecimal bigDecimal = feilv.setScale(1, BigDecimal.ROUND_DOWN);
        double value = bigDecimal.doubleValue();
        //设置费率不能超过1.5改为2.0，最低不能低于0.1
        if(value >2.0 || value < 0.1){
            throw new ProjectException(ResultEnum.RATE_IS_ABNORMAL);
        }
        return bigDecimal;
    }
}
